//
//  CameraPlacesAlert.swift
//  ZhiTing
//
//  Created by iMac on 2022/4/27.
//

import Foundation
import UIKit

class CameraPlacesAlert: UIView {
    var items = [CameraCommonPlaceModel]()
    //点击回调
    var clickCallback: ((_ index: Int) -> ())?
    //删除回调
    var deletedCallback: ((_ places: [CameraCommonPlaceModel]) -> ())?

    var isEdit = false {
        didSet {
            collectionView.reloadData()
            deleteBtn.isHidden = !isEdit
            cancelBtn.isHidden = !isEdit
            editBtn.isHidden = isEdit
        }
    }
    
    lazy var emptyView = EmptyStyleView(frame: .zero, style: .noCollection).then {
        $0.backgroundColor = .custom(.white_ffffff)
        $0.isHidden = true
    }
    
    private lazy var cover = UIView().then {
        $0.backgroundColor = .black.withAlphaComponent(0.3)
        $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss)))
    }
    
    private lazy var container = UIView().then {
        $0.backgroundColor = .custom(.white_ffffff)
        $0.layer.cornerRadius = 10
    }
    
    private lazy var titleLabel = Label().then {
        $0.font = .font(size: 16, type: .bold)
        $0.textColor = .custom(.black_333333)
        $0.text = "常看位置".localizedString
    }
    
    private lazy var closeBtn = Button().then {
        $0.setImage(.assets(.close_button), for: .normal)
        $0.isEnhanceClick = true
        $0.clickCallBack = { [weak self] _ in
            self?.dismiss()
        }
    }

    private lazy var line = UIView().then {
        $0.backgroundColor = .custom(.gray_eeeeee)
    }
    
    private lazy var cancelBtn = Button().then {
        $0.setTitle("取消".localizedString, for: .normal)
        $0.setTitleColor(.custom(.blue_2da3f6), for: .normal)
        $0.titleLabel?.font = .font(size: 14, type: .medium)
        $0.layer.cornerRadius = 10
        $0.layer.borderWidth = 0.5
        $0.layer.borderColor = UIColor.custom(.blue_2da3f6).cgColor
        $0.isHidden = true
        $0.clickCallBack = { [weak self] _ in
            self?.isEdit = false
        }
    }
    
    private lazy var deleteBtn = Button().then {
        $0.setTitle("删除".localizedString, for: .normal)
        $0.setTitleColor(.custom(.white_ffffff), for: .normal)
        $0.titleLabel?.font = .font(size: 14, type: .medium)
        $0.layer.cornerRadius = 10
        $0.backgroundColor = .custom(.blue_2da3f6)
        $0.isHidden = true
        $0.clickCallBack = { [weak self] _ in
            self?.deletedAction()
        }
    }
    
    private lazy var editBtn = Button().then {
        $0.setTitle("编辑".localizedString, for: .normal)
        $0.setTitleColor(.custom(.blue_2da3f6), for: .normal)
        $0.titleLabel?.font = .font(size: 14, type: .medium)
        $0.layer.cornerRadius = 10
        $0.layer.borderWidth = 0.5
        $0.layer.borderColor = UIColor.custom(.blue_2da3f6).cgColor
        $0.clickCallBack = { [weak self] _ in
            self?.isEdit = true
        }
    }

    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let itemW = (Screen.screenWidth - 45) / 2
        let itemH = itemW * 22 / 33 + 50
        layout.itemSize = CGSize(width: itemW, height: itemH)
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15

        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        cv.register(CameraPlacesAlertCell.self, forCellWithReuseIdentifier: CameraPlacesAlertCell.reusableIdentifier)
        return cv

    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupConstraints()
    }
    
    convenience init() {
        self.init(frame: CGRect(x: 0, y: 0, width: Screen.screenWidth, height: Screen.screenHeight))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        addSubview(cover)
        addSubview(container)
        container.addSubview(titleLabel)
        container.addSubview(closeBtn)
        container.addSubview(line)
        container.addSubview(collectionView)
        container.addSubview(emptyView)
        container.addSubview(cancelBtn)
        container.addSubview(deleteBtn)
        container.addSubview(editBtn)

    }
    
    private func setupConstraints() {
        cover.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        
        container.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.bottom.equalToSuperview().offset(10)
            $0.height.equalTo(Screen.screenHeight * 4 / 5)
        }
        
        titleLabel.snp.makeConstraints {
            $0.top.equalToSuperview().offset(16)
            $0.left.equalToSuperview().offset(16)
        }
        
        closeBtn.snp.makeConstraints {
            $0.centerY.equalTo(titleLabel.snp.centerY)
            $0.right.equalToSuperview().offset(-16)
            $0.height.width.equalTo(12)
        }
        
        line.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.height.equalTo(0.5)
            $0.top.equalTo(titleLabel.snp.bottom).offset(16)
        }
        
        collectionView.snp.makeConstraints {
            $0.top.equalTo(line.snp.bottom).offset(15)
            $0.right.equalToSuperview().offset(-15)
            $0.left.equalToSuperview().offset(15)
            $0.bottom.equalTo(cancelBtn.snp.top).offset(-10)
        }
        
        emptyView.snp.makeConstraints {
            $0.top.equalTo(line.snp.bottom).offset(15)
            $0.right.equalToSuperview().offset(-15)
            $0.left.equalToSuperview().offset(15)
            $0.bottom.equalTo(cancelBtn.snp.top).offset(-10)
        }

        cancelBtn.snp.makeConstraints {
            $0.left.equalToSuperview().offset(15)
            $0.height.equalTo(50)
            $0.width.equalTo((Screen.screenWidth - 45) / 2)
            $0.bottom.equalToSuperview().offset(-Screen.bottomSafeAreaHeight - 20)
        }
        
        deleteBtn.snp.makeConstraints {
            $0.right.equalToSuperview().offset(-15)
            $0.height.equalTo(50)
            $0.width.equalTo((Screen.screenWidth - 45) / 2)
            $0.bottom.equalToSuperview().offset(-Screen.bottomSafeAreaHeight - 20)
        }
        
        editBtn.snp.makeConstraints {
            $0.left.equalToSuperview().offset(15)
            $0.height.equalTo(50)
            $0.right.equalToSuperview().offset(-15)
            $0.bottom.equalToSuperview().offset(-Screen.bottomSafeAreaHeight - 20)
        }

    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        container.transform = .init(translationX: 0, y: Screen.screenHeight)
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
            self.container.transform = .identity
        }

    }
    
    override func removeFromSuperview() {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
            self.container.transform = .init(translationX: 0, y: Screen.screenHeight)
        }, completion: { isFinished in
            if isFinished {
                super.removeFromSuperview()
            }
        })
        
    }
    
    @objc
    private func dismiss() {
        removeFromSuperview()
    }
    
    @objc
    private func deletedAction(){
        let result = items.filter({ $0.isSelected == true })
        deletedCallback?(result)
        dismiss()
    }

}


extension CameraPlacesAlert: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CameraPlacesAlertCell.reusableIdentifier, for: indexPath) as! CameraPlacesAlertCell
        cell.isEdit = isEdit
        let model = items[indexPath.item]
        cell.image.image = UIImage(data: model.commonPlaceData)
        cell.titleLabel.text = model.placeName
        cell.selectBtn.isSelected = model.isSelected
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if isEdit {
            items[indexPath.item].isSelected = !items[indexPath.item].isSelected
            collectionView.reloadData()
        }else{
            clickCallback?(indexPath.item)
            dismiss()
        }
    }

}






fileprivate class CameraPlacesAlertCell: UICollectionViewCell, ReusableView {
    var isEdit = false {
        didSet {
            selectBtn.isHidden = !isEdit
        }
    }

    lazy var image = ImageView().then {
        $0.contentMode = .scaleToFill
        $0.layer.cornerRadius = 4
        $0.backgroundColor = .custom(.gray_f6f8fd)
    }
    
    lazy var selectBtn = SelectButton(type: .square).then {
        $0.isHidden = true
        $0.isUserInteractionEnabled = false
    }
    
    lazy var titleLabel = Label().then {
        $0.font = .font(size: 14, type: .bold)
        $0.textColor = .custom(.black_333333)
        $0.text = "junjing"
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        contentView.addSubview(image)
        contentView.addSubview(selectBtn)
        contentView.addSubview(titleLabel)
    }
    
    private func setupConstraints() {
        let itemW = (Screen.screenWidth - 45) / 2
        let itemH = itemW * 22 / 33
        image.snp.makeConstraints {
            $0.top.left.right.equalToSuperview()
            $0.height.equalTo(itemH)
        }
        
        selectBtn.snp.makeConstraints {
            $0.width.height.equalTo(18)
            $0.top.equalToSuperview().offset(10)
            $0.right.equalToSuperview().offset(-10)
        }

        
        titleLabel.snp.makeConstraints {
            $0.top.equalTo(image.snp.bottom).offset(14)
            $0.left.equalToSuperview().offset(15)
        }

    }
}
